﻿#region Copyright (c) 2013-05, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Windows.Input;


namespace Amarok.Presentation
{
	/// <summary>
	/// This type represents a view command.
	/// 
	/// View commands are used to forward specific user actions (commands) from the view to the associated 
	/// controller. Instances of view commands are held in a view's view model bridging the gap between view 
	/// and controller. When the view executes a data-bound command the callback method supplied on construction 
	/// is called, basically delegating the handling of the user action to the associated controller.
	/// </summary>
	/// 
	/// <typeparam name="T">
	/// The type of the command parameter supplied to the command's methods.</typeparam>
	public class ViewCommand<T> :
		ICommand,
		IDisposable
	{
		// data
		private readonly Action<T> mExecuteCallback;
		private readonly Func<T, Boolean> mCanExecuteCallback;
		private readonly Boolean mIgnoreNullParameters;

		// state
		private Boolean mIsDisposed;


		#region ++ IDisposable Interface ++

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		void IDisposable.Dispose()
		{
			mIsDisposed = true;
		}

		#endregion

		#region ++ ICommand Interface ++

		/// <summary>
		/// Occurs when changes occur that affect whether or not the command should execute.
		/// </summary>
		public event EventHandler CanExecuteChanged
		{
			add
			{
				if (mCanExecuteCallback != null)
				{
					CommandManager.RequerySuggested += value;
				}
			}
			remove
			{
				if (mCanExecuteCallback != null)
				{
					CommandManager.RequerySuggested -= value;
				}
			}
		}


		/// <summary>
		/// The method determines whether the command can execute in its current state.
		/// </summary>
		/// 
		/// <param name="parameter">
		/// Data used by the command. If the command does not require data to be passed, this object 
		/// can be set to null.</param>
		/// 
		/// <returns>
		/// true if this command can be executed; otherwise, false.</returns>
		public virtual Boolean CanExecute(Object parameter)
		{
			if (mIsDisposed)
				return false;
			if (parameter == null && mIgnoreNullParameters)
				return false;
			if (mCanExecuteCallback == null)
				return true;

			var result = mCanExecuteCallback((T)parameter);

			#region (hooks: can execute)
			ViewCommandHooks.RaiseCanExecuteCalled(mCanExecuteCallback);
			#endregion

			return result;
		}

		/// <summary>
		/// The method to be called when the command is invoked.
		/// </summary>
		/// 
		/// <param name="parameter">
		/// Data used by the command. If the command does not require data to be passed, this object 
		/// can be set to null.</param>
		public virtual void Execute(Object parameter)
		{
			if (mIsDisposed)
				return;
			if (parameter == null && mIgnoreNullParameters)
				return;

			mExecuteCallback((T)parameter);

			#region (hooks: execute)
			ViewCommandHooks.RaiseExecuteCalled(mExecuteCallback);
			#endregion
		}

		#endregion

		#region ++ Public Interface ++

		/// <summary>
		/// Gets a boolean value indicating whether the object has been disposed.
		/// </summary>
		/// 
		/// <value>
		/// True, if the object is disposed; otherwise False.</value>
		public Boolean IsDisposed
		{
			get
			{
				return mIsDisposed;
			}
		}


		/// <summary>
		/// Initializes a new instance.
		/// </summary>
		/// 
		/// <param name="executeCallback">
		/// A callback method called when executing the command.</param>
		/// <param name="canExecuteCallback">
		/// A callback method called to determine whether the command can be executed.</param>
		/// <param name="ignoreNullParameters">
		/// A boolean value indicating whether calls with null parameter should be ignored.</param>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		public ViewCommand(
			Action<T> executeCallback,
			Func<T, Boolean> canExecuteCallback = null,
			Boolean ignoreNullParameters = true)
		{
			Verify.NotNull(executeCallback, "executeCallback");

			mExecuteCallback = executeCallback;
			mCanExecuteCallback = canExecuteCallback;
			mIgnoreNullParameters = ignoreNullParameters;
		}


		/// <summary>
		/// Raises the <see cref="ICommand.CanExecuteChanged"/> event.
		/// </summary>
		public virtual void RaiseCanExecuteChanged()
		{
			CommandManager.InvalidateRequerySuggested();
		}

		#endregion

	}
}
